package com.efast.cafe.commponent.statemach.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.efast.cafe.commponent.crud.service.impl.CrudSqlGenerateUtils;
import com.efast.cafe.framework.jdbc.JdbcDao;
import com.efast.cafe.portal.bean.common.EntityFieldInfoBean;
import com.efast.cafe.portal.bean.common.EntityInfoBean;
import com.efast.cafe.commponent.statemach.bean.PortalStateMachResourceBean;
import com.efast.cafe.commponent.statemach.dao.PortalStateMachResourceDao;
import com.efast.cafe.portal.remote.common.EntityInfoQueryService;
import com.efast.cafe.commponent.statemach.service.IPortalStateMachResourceService;
@Service
@Transactional
public class PortalStateMachResourceServiceImpl implements IPortalStateMachResourceService{
	
	@Autowired
	private EntityInfoQueryService queryService;	
	
	@Autowired
	private CrudSqlGenerateUtils crudSqlGenerateUtils;

	@Autowired
	private JdbcDao jdbcDao;
	
	@Autowired
	private PortalStateMachResourceDao stateMachResourceDao;
	
	@Override
	public Long insertResource(PortalStateMachResourceBean resource) {
		// 获取扩展类型
		// String extTableName =
		// JSON.parseObject(resource.getParaJson()).getString("extTableName");

		// 同步插入

		stateMachResourceDao.insertResource(resource);
		// 保存图片
//		List<PortalAttachmentForm> attachments = resource.getAttachments();
//		if (attachments != null && attachments.size() > 0) {
//			portalAttachmentService.saveAttachmentForm(resource.getFormId(), attachments);
//
//		}
		if (resource.getExtTableName() != null && !resource.getExtTableName().equals("fms_resource")) {
			List<Object> params = new ArrayList<>();
			EntityInfoBean en = queryService.queryEntityInfo(resource.getExtTableName());
			// 获取参数
			Map<String, Object> param = new HashMap<String, Object>();
			for (int k = 0; k < en.getAttrs().size(); k++) {
				if (JSON.parseObject(resource.getParaJson())
						.getString(en.getAttrs().get(k).getField().getFieldName()) != null) {
					param.put(en.getAttrs().get(k).getField().getFieldName(), JSON.parseObject(resource.getParaJson())
							.getString(en.getAttrs().get(k).getField().getFieldName()));
				}
			}

			String sql = crudSqlGenerateUtils.buildInsertSql(en.getTableName(), param, en.getAttrs(), en.getExtAttrs(),
					false, params);
			sql = sql + ", id = ? ";// 插入ID
			params.add(resource.getId());// 插入ID参数
			jdbcDao.executeBySQL(sql, params);
		}

		return resource.getId();
	}

	@Override
	public Long updateResource(PortalStateMachResourceBean resource) {
		// 获取扩展类型
		// String extTableName =
		// JSON.parseObject(resource.getParaJson()).getString("extTableName");
		//int optCounter = stateMachResourceDao.queryOptCounter(resource.getId());
		//resource.setOptCounter(optCounter);
		stateMachResourceDao.updateResource(resource);

		// 保存图片
//		List<PortalAttachmentForm> attachments = resource.getAttachments();
//		if (attachments != null && attachments.size() > 0) {
//			portalAttachmentService.saveAttachmentForm(resource.getFormId(), attachments);
//		}
		if (resource.getExtTableName() != null && !resource.getExtTableName().equals("fms_resource")) {
			EntityInfoBean en = queryService.queryEntityInfo(resource.getExtTableName());
			// 获取参数
			Map<String, Object> param = new HashMap<String, Object>();
			for (int k = 0; k < en.getAttrs().size(); k++) {
				if (JSON.parseObject(resource.getParaJson())
						.getString(en.getAttrs().get(k).getField().getFieldName()) != null) {
					param.put(en.getAttrs().get(k).getField().getFieldName(), JSON.parseObject(resource.getParaJson())
							.getString(en.getAttrs().get(k).getField().getFieldName()));
				}
			}
			List<Object> params = new ArrayList<>();
			param.put("id", resource.getId());
			String sql = crudSqlGenerateUtils.buildUpdateSql(en.getTableName(), param, en.getAttrs(), en.getExtAttrs(),
					false, params);
			// 同步更新
			jdbcDao.executeBySQL(sql, params);
		}

//		if (resource.getExtTableName().equals("fms_vehicle")) {
//			this.updateVehicleInformation(resource);
//		}

		return resource.getId();
	}

	@Override
	public void deleteResource(PortalStateMachResourceBean resource) {
		// 获取扩展类型
		stateMachResourceDao.deleteResource(resource);
	}
	
	@Override
	public void startAndStop(PortalStateMachResourceBean resourceTaskBean) {
		stateMachResourceDao.startAndStop(resourceTaskBean);

	}
	
	/**
	 * 锁定解锁资源
	 * 
	 * @param isLock
	 * @param taskId
	 */
	@Override
	public void lockResource(int isLock, Long taskId) {
		stateMachResourceDao.lockResource(isLock, taskId);
	}
	
	/**
	 * 根据类型和id获取资源
	 */
	@Override
	public Object getResource(String type, Long id, boolean isExt) {
		EntityInfoBean en = new EntityInfoBean();
		if (isExt) {
			en = queryService.queryEntityInfo(type);
		}
		String sql = getResourceSql(type, id, isExt, en, "resource");
		List<Object> params = new ArrayList<>();
		List<Map<String, Object>> data = jdbcDao.queryForListMap(sql, params);
		Map<String, Object> ret = null;
		ret = data != null && data.size() > 0 ? data.get(0) : null;
		return ret;
	}
	
	/**
	 * 构建查找资源sql
	 * 
	 * @param type
	 * @param id
	 * @return
	 */
	private String getResourceSql(String type, Long id, boolean isExt, EntityInfoBean en, String idType) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT t.id,t.resName,t.resDesc");
		if (isExt) {
			// EntityInfoBean en = queryService.queryEntityInfo(type);
			if (en != null) {
				for (EntityFieldInfoBean filed : en.getAttrs()) {
					if (filed.getField().getIsPk().intValue() == 1) {
						continue;
					}
					sql.append(",ex.");
					sql.append(filed.getField().getPhysicalField());
				}
			}
			sql.append(" from fms_resource t left join ");
			sql.append(type);
			sql.append(" ex on t.id = ex.id ");
		} else {
			sql.append(" from fms_resource t ");
		}
		if (idType.equals("resource")) {
			sql.append(" where t.id = " + id.toString());
		} else if (idType.equals("task")) {
			sql.append(" where t.id = (SELECT relid FROM fms_resource_task WHERE taskId = ");
			sql.append(id.toString());
			sql.append(" and relObjectName = '");
			sql.append(type);
			sql.append("' limit 1)");
		}
		return sql.toString();
	}
}
